package com.blb.goods_service.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.connection.RedisConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Redis的配置类
 */
@Configuration
public class RedisConfig {

    /**
     * 配置编程式缓存需要的RedisTemplate对象
     * @param factory
     * @return
     */
    @Bean
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
        //创建Template对象
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        //设置连接工厂
        template.setConnectionFactory(factory);
        //创建Jackson的JSON序列化器
        Jackson2JsonRedisSerializer objSerializer = new Jackson2JsonRedisSerializer(Object.class);
        //创建对象映射器
        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        //配置映射器
        objSerializer.setObjectMapper(mapper);
        //创建字符串序列化器
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        //给template配置键的序列化器
        template.setHashKeySerializer(stringRedisSerializer);
        template.setKeySerializer(stringRedisSerializer);
        //配置值的序列化器
        template.setHashValueSerializer(objSerializer);
        template.setValueSerializer(objSerializer);
        template.afterPropertiesSet();
        return template;
    }

    /**
     * 配置声明式缓存配置对象
     * @return
     */
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration(){
        //获得默认的配置对象
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        //配置序列化器
        config.serializeValuesWith(RedisSerializationContext
                .SerializationPair
                .fromSerializer(new GenericJackson2JsonRedisSerializer()));
        return config;
    }
}
